package com.example.newproject_overseas.ViewModel

import CryptUtils
import android.content.Context
import android.util.Log
import android.widget.Toast
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.example.newproject_overseas.model.entity.LoginRequestModel
import com.example.newproject_overseas.model.entity.LoginUser
import com.example.newproject_overseas.model.entity.PhoneModel
import com.example.newproject_overseas.model.entity.WreakRequestModel
import com.example.newproject_overseas.model.entity.WreakResponseModel
import com.example.newproject_overseas.model.service.LoginService
import com.example.newproject_overseas.model.service.MisanthropeService
import com.example.newproject_overseas.model.service.UserInfoManager
import com.google.gson.Gson
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.firstOrNull
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.RequestBody

class LoginViewModel(context: Context): ViewModel() {


    // 获得用户信息
    private val _loginUser = MutableStateFlow<LoginUser?>(null)
    val localLoginUser: StateFlow<LoginUser?> = _loginUser


    // 加载等待状态
    val loading: MutableState<Boolean> = mutableStateOf(false)

    var context_cur:Context = context

    private val misanthropeService = MisanthropeService.instance()

    private val loginService = LoginService.instance()

    val userInfoManager = UserInfoManager(context)

    init {
        //其实这里可以使用 DataStore 的对象存储，直接存储整个对象
        viewModelScope.launch {
            userInfoManager.loginUser.collect { jsonStr ->
                val loginUser = Gson().fromJson(jsonStr, LoginUser::class.java)
                _loginUser.value = loginUser
            }
        }
    }



    var loginUser : LoginUser? = null
        private set

    //是否已登陆
    val logged: Boolean
        get(){
            return loginUser != null
        }

    //电话
    var LoginPagePhoneNumber by mutableStateOf("8888111101")
    //验证码
    var Verificationcode by mutableStateOf("123456")
    //是否同意协议
    var RadioButtonValue by mutableStateOf(false)
    val annotatedString = buildAnnotatedString {
        withStyle(SpanStyle(color = Color.Black, fontSize = 12.sp)) {
            append("I have read and agreed ")

        }
        withStyle(SpanStyle(color = Color(0xfffecb2f), fontSize = 12.sp)) {
            append("(Loan House's Privacy Agreement Conditions and Terms) ")
            addStringAnnotation("Clickable", "ClickableText", 0, length)
        }
        withStyle(SpanStyle(color = Color.Black, fontSize = 12.sp)) {
            append(" the agreement is highlighted,clickto view, the agreement is checked by default and you can click to cancel the check")
        }
    }


    suspend fun loginLogic(navController: NavHostController) {

        try {

            loading.value = true // 开始加载
            val loginModel = LoginRequestModel(LoginPagePhoneNumber,"+91",Verificationcode)
            val loginRes = loginService.UserLogin(loginModel)
            if (loginRes.status == 0){
                userInfoManager.save(loginRes.user)
                navController.navigate("MainFrame" )
                Toast.makeText(context_cur,"Login successful", Toast.LENGTH_SHORT).show()
            }

        }finally {
            loading.value = false // 结束加载
        }
    }

    suspend fun optLogic() {

        val phoneModel = PhoneModel("8888111101", "+91")
        val wreakRequestModel = WreakRequestModel(phoneModel)

        val response = misanthropeService.postWreakRequest(wreakRequestModel);
        Log.i("resStr", response.time.toString())
    }


    // 导航栏我的页面最底下的文字
    val my_last = buildAnnotatedString {
        withStyle(SpanStyle(color = Color(0xff636363 ), fontSize = 12.5.sp)) {
            append("Used by over ")
        }
        withStyle(SpanStyle(color = Color(0xffFFCC00 ), fontSize = 12.5.sp)) {
            append("170,000 ")
            addStringAnnotation("Clickable", "ClickableText", 0, length)
        }
        withStyle(SpanStyle(color =  Color(0xff636363 ), fontSize = 12.5.sp)) {
            append("people")
        }
    }
}